<?php

namespace app\admin\controller\superdata;
use app\admin\model\Admin;
use app\admin\model\AdminBasicZoom;
use app\admin\model\AuthGroupAccessZoom;
use app\admin\model\superdata\Activity;
use app\admin\model\superdata\Seriesactivity;
use app\admin\model\vactivities\Ticket;
use app\common\controller\Backend;
use Exception;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 账号管理
 *
 * @icon fa fa-circle-o
 */
class Account extends Backend
{
    
    /**
     * Account模型对象
     * @var \app\admin\model\superdata\Account
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\superdata\Account;
        $this->view->assign("sourceList", $this->model->getSourceList());
        $this->view->assign("tlsList", $this->model->getTlsList());
        $this->view->assign("isoldList", $this->model->getIsoldList());
        $accmodel = new \app\admin\model\superdata\Account;
        $this->view->assign('headList', $accmodel->getHeadingList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id', 'username', 'nickname', 'mobile', 'activity_count','series_count','total_income','order_count','no']);
                $row['activity_count'] = Activity::getActCntByAdmId($row['id']);
                if (empty($row['activity_count'])) {
                    $row['activity_count'] = 0;
                }
                $row['series_count'] = Seriesactivity::getSeriesCntByAdmId($row['id']);
                if (empty($row['series_count'])) {
                    $row['series_count'] = 0;
                }
                $row['total_income'] = 0;
                $row['order_count'] = 0;
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $this->view->assign('now_function', 'superdata/account/index');
        return $this->view->fetch();
    }


    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $repassword = $this->request->post("repassword");
          //  print_r($repassword);
           // echo '----';
            //print_R($params);die;
            // 处理数据
            if($params['password'] !=$repassword){
                $this->error('密码与确认密码必须一致', null, ['token' => $this->request->token()]);
            }
            $params['salt'] = pwdSalt();
            $params['password'] = md5(md5($params['password']) . $params['salt']);
            $params['createtime'] = time(); //创建时间为当前时间
            $params['updatetime'] = time(); //更新时间为当前时间
            $params['serial'] = selfserial();
            $avatar = $params['avatar'];
            $params['avatar'] = !empty($avatar) ? $avatar : config('default_avatar');
            $params['joinip'] = request()->ip(0,false);
            $params['loginip'] = request()->ip(0,false);
            $params['token_zoom'] = zoom_token();//来自zoom表中的token
            $params['username'] = $params['mobile'];
            $params['source'] = \app\admin\model\Account::USER_SOURCE_99;//用户来源 99 代表onzoom用户

            if ($params) {
                $params = $this->preExcludeFields($params);
                $config = $this->model->get($params);
                if($config){
                    return $this->error('用户名或手机号已经存在,请换其它号');
                }
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);


                    //3、创建admin用户
                    // 获取admin表的字段名称
                    $admin_field = Db::name('admin')->getTableFields();
                    $admin_params = array_filter(array_intersect_key($params, array_flip($admin_field)));
                    $admin_params['account_id'] = $this->model->id;

                    $admin = new Admin();
                    $result_admin = $admin->save($admin_params);
                    if (!$result_admin){
                        $this->error('注册失败，请重试', null, ['token' => $this->request->token()]);
                    }

                    //4 创建Zoom用户基本信息表
                    $basic_admin['account_id'] = $this->model->id;
                    $basic_admin['admin_id'] = $admin['id'];
                    $basic_admin['serial'] = $params['serial'];
                    $basic_admin['avatar'] = $params['avatar'];
                    $basic_admin['ctime'] = time();
                    $basic_admin['source'] = $params['source'];
                    $basic_admin['joinip'] = $params['joinip'];
                    $basic_admin['loginip'] = $params['loginip'];

                    $admin_basic =  new AdminBasicZoom();//注册用户基本信息表
                    $admin_basic_r = $admin_basic->save($basic_admin);
                    if (!$admin_basic_r){
                        $this->error('用户基本信息注册失败，请重试', null, ['token' => $this->request->token()]);
                    }

                    $map['uid'] = $admin['id'];
                    $admin_count = Db::name('auth_group_access_zoom')
                        ->where($map)
                        ->count();

                    if (!$admin_count){//当没有举办人的权限时加入举办的角色
                        $aga_result = AuthGroupAccessZoom::create(['uid'=>$admin['id'], 'group_id'=>AuthGroupAccessZoom::SPONSOR]);
                        if ($aga_result === false) {
                            $this->error(model('AuthGroupAccessZoom')->getError());
                        }
                    }
                    unset($map);
                    unset($basic_admin);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

}
